﻿#region Imports
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.VisualBasic;
#endregion

namespace IntelliSearch.Utilities
{
    /// <summary>
    /// Exposes extensions methods
    /// </summary>
    public static class Extensions
    {
        #region Methods
        /// <summary>
        /// Converts a character array to string
        /// </summary>
        /// <param name="value">Character array</param>
        /// <returns>String containing merged characters</returns>
        public static string ToCharString(this IEnumerable<char> value, string separator = "")
        {
            string str = "";
            if (value != null) value.ToList().ForEach(chr => str += chr + separator);

            return str.TrimEnd(separator);
        }

        public static string Trim(this string value, string trimText)
        {
            return value.TrimStart(trimText).TrimEnd(trimText);
        }

        public static string TrimStart(this string value, string trimText)
        {
            if (value.Length * trimText.Length > 0)
                while (Strings.Left(value, trimText.Length) == trimText)
                    value = value.ToCharArray().Reverse().Take(value.Length - trimText.Length).Reverse().ToCharString();

            return value;
        }

        public static string TrimEnd(this string value, string trimText)
        {
            if (value.Length * trimText.Length > 0)
                while (Strings.Right(value, trimText.Length) == trimText)
                    value = value.ToCharArray().Take(value.Length - trimText.Length).ToCharString();

            return value;
        }

        public static string ToFormattedNullString(this string value)
        {
            return !value.IsNullOrEmpty() ? value : String.Empty;
        }

        public static bool IsNullOrEmpty(this string value)
        {
            return String.IsNullOrEmpty(value);
        }

        public static string Left(this string value, int length)
        {
            return Strings.Left(Convert.ToString(value), length);
        }

        public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> value)
            where T : new()
        {
            return new ObservableCollection<T>(value);
        }

        public static IEnumerable<T> Unions<T>(this IEnumerable<T> value, params IEnumerable<T>[] append)
            where T : new()
        {
            IEnumerable<T> temp = value;
            append.ToList().ForEach(add => temp = temp.Union(add));

            return temp.Distinct();
        }
        #endregion
    }
}
